
package com.android.finaltracer.channel;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;
import android.util.Log;

import com.android.finaltracer.model.DataFormatBasic;
import com.android.finaltracer.model.DataFormatFactory;
import com.android.finaltracer.model.DataFormatInterface;
import com.android.finaltracer.util.FinalTracerIntents;

public class Sms extends Channel {
    private Context mContext;

    public Sms(Context context, ChannelEventCallback cb) {
        super(cb);
        mContext = context;
        IntentFilter filter = new IntentFilter();
        filter.addAction(FinalTracerIntents.SMS_INTERACT);
        mContext.registerReceiver(mReceiver, filter);
    }

    public BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null || action.length() == 0) {
                return;
            }
            String from = intent.getStringExtra(TAG_FROM);
            String body = intent.getStringExtra(TAG_BODY);
            Log.i("Sms", "sms receive body=" + body);
            DataFormatInterface dfb = DataFormatFactory.createInstance(body);
            if (dfb != null) {
                mCallback.onReceive(from, dfb);
            }
        }
    };

    @Override
    public void send(String target, DataFormatBasic dataFormatBasic) {
        String jsString = dataFormatBasic.encode();
        if (jsString != null) {
            SmsManager sms = SmsManager.getDefault();
            Log.i("Sms", "sms send msg;" + jsString);
            sms.sendTextMessage(target, null, jsString.replace("{", "(")
                    .replace("}", ")"), null, null);
        }
    }
}
